import { ObjectId } from "mongodb";
import { Injectable } from "@nestjs/common";
import { Core } from "./core";

@Injectable()
export class AppService {
    // private client: MongoClient;
    // private db: Db;

    constructor() {
        // const url = "mongodb://admin:jsz04005301@120.48.63.39:27017";
        // this.client = new MongoClient(url);
        // this.connect();
    }

    public async getAll(): Promise<string> {
        const collection = Core.ins.db.collection("books");
        const ary = await collection.find({}).toArray();
        return JSON.stringify(ary);
    }

    public async getOne(id: string): Promise<string> {
        const collection = Core.ins.db.collection("books");
        const ary = await collection.findOne({ _id: new ObjectId(id) });
        return JSON.stringify(ary);
    }

    public async addOne(name: string): Promise<string> {
        const collection = Core.ins.db.collection("books");
        const insertResult = await collection.insertOne({
            name: name,
            age: Math.floor(Math.random() * 100),
            time: new Date()
        });
        return insertResult.insertedId.toString();
    }

    public async deleteOne(id: string): Promise<string> {
        const collection = Core.ins.db.collection("books");
        const insertResult = await collection.deleteOne({ _id: new ObjectId(id) });
        return insertResult.deletedCount.toString();
    }
}
